<?php

namespace app\admin\controller\goods;

use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 商品分类
 *
 * @icon fa fa-circle-o
 */
class Index extends Backend
{

    /**
     * Index模型对象
     * @var \app\admin\model\goods\Index
     */
    protected $model = null;
    protected $rulelist = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\goods\Index;

//        $this->model = model('Goods');
//        $this->model = model('AuthRule');
        // 必须将结果集转换为数组
        $ruleList = \think\Db::name("cate_goods")->field('update_time', true)->order('id ASC')->select();
//        $ruleList = \think\Db::name("auth_rule")->field('type,condition,remark,createtime,updatetime', true)->order('weigh DESC,id ASC')->select();
        foreach ($ruleList as $k => &$v) {
            $v['title'] = __($v['title']);
        }
        unset($v);
        Tree::instance()->init($ruleList);
        $this->rulelist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0), 'title');

        $ruledata = [0 => __('None')];

        foreach ($this->rulelist as $k => &$v) {
            if (!$v['pid']) {
                continue;
            }
            $ruledata[$v['id']] = $v['title'];
            unset($v['spacer']);
        }
        unset($v);


//        echo "<pre>";
//        print_r($this->rulelist);exit;
//        $this->view->assign('data', $ruledata);
        $this->view->assign('cate',Db::name('cate_goods')->where('pid',0)->field('id,title')->select());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
//            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->rulelist;
            if($list){

                foreach($list as &$val)
                {
                    switch($val['status'])
                    {
                        case 1;
                            $val['status'] = '是';
                            break;
                        case 2;
                            $val['status'] = '否';
                            break;
                    }
                }
            }
            $total = count($this->rulelist);
//            $result = array("total" => $list->total(), "rows" => $list->items());
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $cate = Db::name('cate_goods')->where('id',$ids)->find();

                $data['title'] = $params['title'] ? $params['title'] : $cate['title'];
                $data['status'] = $params['status'] ? $params['status'] : $cate['status'];
                $data['image'] = $params['image'] ? $params['image'] : $cate['image'];
                
                if(empty($cate['pid']) && !empty($params['pid']))$this->error('属于栏目请选择无');
                $data['pid'] = $params['pid'] ? $params['pid'] : $cate['pid'];
                $data['update_time'] = time();
                
                $res = Db::name('cate_goods')->where('id',$ids)->update($data);
                if($res)
                {
                    $this->success(__('修改成功'));
                }else{
                    $this->error(__('修改失败'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $status = [['id'=>'1','status'=>'是'],['id'=>'2','status'=>'否']];
        $this->view->assign('cate',Db::name('cate_goods')->where('pid',0)->field('id,title')->select());
        $this->view->assign('pid',Db::name('cate_goods')->where('id',$row['id'])->value('pid'));
        $this->view->assign('status',Db::name('cate_goods')->where('id',$row['id'])->value('status'));
        $this->view->assign('sta',$status);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if(!$params['title'])$this->error(__('请输入类目'));
                if(!$params['image'])$this->error(__('请选择图片'));


                $data = ['title'=>$params['title'],'image'=>$params['image'],'pid'=>$params['pid'],'create_time'=>time()];

                $res  = Db::name('cate_goods')->insert($data);
                if($res)
                {
                    $this->success('添加成功');
                }else{
                    $this->error('添加失败');
                }

            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

}
